package com.huobi.pro.trade;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.huobi.db.bean.TradeOrder;
import com.huobi.db.mapper.TradeOrderMapper;
import com.huobi.pro.trade.TradeService.Status;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ResumeTradeService {

	@Autowired TradeOrderMapper tradeOrderMapper;
	@Autowired TradeService tradeService;

	@Scheduled(cron = "0/1 * * * * ?")
	public void resume() throws InterruptedException {
		List<TradeOrder> orders = new ArrayList<>();
		
		tradeOrderMapper.selectByStatus(Status.WAITING.getValue()).forEach(v->{
			orders.add(v);
		});
		
		tradeOrderMapper.selectByStatus(Status.PENDING.getValue()).forEach(v->{
			orders.add(v);
		});

		orders.forEach(order->{
			if(order.getStatus().equals(Status.WAITING.getValue())) {
				resumeOrder(orders);
			}
			if(order.getStatus().equals(Status.PENDING.getValue())) {
				queryOrder(orders);
			}
		});
		
	}

	private void queryOrder(List<TradeOrder> orders) {
		orders.forEach(order -> {
			if (isOvertime(order)) {
				tradeService.cannelOrder(order.getId());
			} else {
				tradeService.queryOrder(order.getId());
			}
		});
	}

	private void resumeOrder(List<TradeOrder> orders) {
		orders.forEach(order -> {
			// 规定时间内没成交就作废
			if (isOvertime(order)) {
				tradeOrderMapper.updateToFailed(order.getId());
			} else {
				tradeService.trade(order.getId());
			}
		});
	}
	
	private boolean isOvertime(TradeOrder order) {
		Long createTime = order.getCreateDate().getTime() / 1000;
		Long currTime = System.currentTimeMillis() / 1000;
		return (currTime - createTime) > 30;
	}

}
